﻿using System;
using System.Collections.Concurrent;
using System.Net.Sockets;
using CommunicationProtocol.dto;
using CommunicationProtocol.dto.command.client;
using CommunicationProtocol.filters;

namespace server.gameLogic
{
    public class AllClientHolder
    {
        public static readonly ConcurrentDictionary<Socket, ClientMetaData> connectedClients =
            new ConcurrentDictionary<Socket, ClientMetaData>();

        public static void register(Socket client)
        {
            SocketSenderFilter socketSenderFilter = new SocketSenderFilter(client);

            connectedClients.TryAdd(client, new ClientMetaData(socketSenderFilter));
        }

        public static void remove(Socket client)
        {
            if (connectedClients.TryRemove(client, out ClientMetaData clientMetaData))
            {
                // 客户端断开连接
                Console.WriteLine($"客户端{client.RemoteEndPoint.ToString()}已断开连接");

                // 先发送关闭连接信号给客户端
                client.Shutdown(SocketShutdown.Both);
                // 然后关闭 socket 并释放资源
                client.Close();
            }
        }

        public static void send(Command command)
        {
            foreach (ClientMetaData clientsValue in connectedClients.Values)
            {
                clientsValue.write(command);
            }
        }

        public static void sendExceptMe(Command command, string userId)
        {
            foreach (ClientMetaData clientsValue in connectedClients.Values)
            {
                if (!Equals(clientsValue.userId,userId))
                {
                    clientsValue.write(command);
                }

            }
        }
    }
}